import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken, getInfos, setInfos, removeInfos } from '@/utils/auth'
import { awaitWrapper } from '@/utils/common'
const state = {
  token: getToken(),
  type: getInfos('type'),
  username: getInfos('username')
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_TYPE: (state, type) => {
    state.type = type
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  }
}
const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(result => {
        if (result.code === 200) {
          const { type } = result
          const info = { type: type, username: username }
          commit('SET_TOKEN', result.data['App-token'])
          commit('SET_TYPE', type)
          commit('SET_USERNAME', username)
          setToken(result.data['App-token'])
          setInfos(JSON.stringify(info))
          resolve(result)
        } else {
          reject(result)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      const [err, result] = awaitWrapper(logout({ token: state.token }))
      if (err) {
        reject(err)
      }
      if (result) {
        commit('SET_TOKEN', '')
        commit('SET_TYPE', '')
        commit('SET_USERNAME', '')
        removeToken()
        removeInfos()
        resolve()
      }
    })
  }
}
export default {
  // namespaced: true,
  state,
  mutations,
  actions
}
